import {
  indexApi
} from '../../api/index';
import {
  request
} from '../../utils/request';
const app = getApp();

Page({
  data: {
    defaultData: {
      title: "我的订单", // 导航栏标题
      // imageSrc: "/images/home.png",
      isBackToPreviousPage: false
    },
    isEmpty: false,//订单是否为空
    isLogin:true,//判断有没有登录
    showEvaluate: false, //显示评价
    keyword: '', // 用于存储用户输入的搜索关键词
    pageNum: 0,
    pageSize: 10,
    tabs: 0,
    title: "",
    status: null,
    tabsTitle: [{
        title: "全部",
        //  status:10
      },
      {
        title: "待支付",
        status: "0"
      }, {
        title: "待接单",
        status: "1"
      }, {
        title: "待确认",
        status: "2"
      }, {
        title: "待上门",
        status: "3"
      }, {
        title: "服务中",
        status: "4"
      }, {
        title: "待验收",
        status: "5"
      }, {
        title: "已完成",
        status: "6"
      }, {
        title: "已评价",
        status: "7"
      }
    ],
    products: [],
    tmpList: [],
  },

  onLoad(){
   
  },

  onShow: function () {
    wx.switchTab({
      url: '/pages/quickOrder/index',
    });
    this.getOrderList();
    this.checkTabsAndShowEvaluate();
    this.checkToken()
  },

  // 检查有没有token
  checkToken(){
    const token = wx.getStorageSync('token');
    if (token) {
      this.setData({
        isLogin:true
      })
      console.log("token",token);
      console.log("isLogin",this.data.isLogin);
    } else {
      this.setData({
        isLogin:false
      })
      console.log("token=====",token);
      console.log("isLogin=======",this.data.isLogin);
    }
  },

  //显示评价
  checkTabsAndShowEvaluate: function () {
    if (this.data.title === "已完成") {
      this.setData({
        showEvaluate: true
      });
    } else {
      this.setData({
        showEvaluate: false
      });
    }
  },

  /**
   * 
   * @param {*} status 为空获取全部订单 
   */
  async getOrderList(status) {
    const that = this
    try {
      let res = null;
      if (status != null) {
        res = await request({
          url: indexApi.ordeApi(),
          data: {
            status: status,
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize,
          }
        });
      } else {
        res = await request({
          url: indexApi.ordeApi(),
          data: {
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize,
          }
        });
      }

      if (res.data.list.length == 0 && status==null) {
        console.log("为空");
        this.setData({
          isEmpty: false
        });
      } else {
        this.setData({
          isEmpty: true
        });
      }

      this.setData({
        products: res.data.list,
        tmpList: res.data.list
      });
      
    } catch (error) {
      console.error("Error:", error);
    }
  },
  // async getOrderList() {
  //   const that = this
  //   try {
  //     const res = await request({
  //       url: indexApi.ordeApi(),
  //       data: {
  //         pageNum: this.data.pageNum,
  //         pageSize: this.data.pageSize,
  //       }
  //     });
  //     const serviceProviderStatus = app.globalData.serviceProviderStatus
  //     console.log("serviceProviderStatus",serviceProviderStatus);
  //     console.log("res.data.list",res.data.list);
  //     if (serviceProviderStatus == 3) {
  //       this.setData({
  //         products: res.data.list,
  //         tabsTitle:this.data.tabsTitleList
  //       })
  //     } else {
  //       // 移除tabsTitle里面status: 1的项
  //       let updatedTabsTitle = this.data.tabsTitleList.filter(tab => tab.status != "1");

  //       // 移除res.data.list里面status: 1的订单
  //       let updatedOrders = res.data.list.filter(order => order.status != 1);

  //       this.setData({
  //         tabsTitle: updatedTabsTitle,
  //         products: updatedOrders
  //       })
  //     }
  //     console.log("ordeApi", res.data.list);
  //   } catch (error) {
  //     console.error("Error:", error);
  //   }
  // },

  // 输入框内容改变事件
  inputChange: function (e) {
    this.setData({
      keyword: e.detail.value
    });
  },
  // 搜索按钮点击事件
  search: function () {
    const keyword = this.data.keyword;
    console.log("搜索关键词：" + keyword);
  },

  /**
   * 点击tab切换调整数据源
   * @param {} event 
   */
  // changeList(event){
  //   let index = event.detail.index;
  //   if (index==0) {
  //     this.data.tmpList = this.data.products;
  //   }else{
  //     let newIndex = index-1;
  //     this.data.tmpList = this.data.products.filter(item=>{
  //       return item.status == newIndex;
  //     })
  //   }
  // },
  /**
   * 后端接口获取数据，每次点击都调用
   * @param {} status 
   */
  changeListByStatus(event) {
    let index = event.detail.index;
    if (index == 0) {
      this.getOrderList(null);
    } else {
      let newIndex = index - 1;
      this.getOrderList(newIndex);
    }
  },
  handleTabChange(event) {
    //this.changeList(event);//前端数据处理，接口调用次数少
    this.changeListByStatus(event); //后端接口刷新数据，每次点击tab都会发送请求
    this.checkTabsAndShowEvaluate(); //获取评论
  },

  // 点击弹框
  clickActions: function (event) {
    const orderId = event.currentTarget.dataset.orderid;
    // console.log("order.status", order.status);
    const order = this.data.products.find(product => product.orderId === orderId);
    console.log("order", order);
    console.log("order.status", order.status);
    if (order) {
      const orderString = encodeURIComponent(JSON.stringify(order));
      let url = '';

      // 根据订单状态设置跳转的页面
      switch (order.status) {
        case 0: // 待支付
          url = `/packageOrder/pages/orderDetails/index?order=${orderString}`;
          break;
        case 1: // 待接单
          url = `/packageOrder/pages/orderDetails/index?order=${orderString}`;
          break;
        case 2: // 待确认
          url = `/packageOrder/pages/orderSure/index?order=${orderString}`;
          break;
        case 3: // 待上门
          url = `/packageOrder/pages/orderDetails/index?order=${orderString}`;
          break;
        case 4: // 服务中
          url = `/packageOrder/pages/orderDetails/index?order=${orderString}`;
          break;
        case 5: // 待验收
          url = `/packageOrder/pages/acceptOrder/index?order=${orderString}`;
          break;
        case 6: // 已完成
          url = `/packageOrder/pages/orderDetails/index?order=${orderString}`;
          break;
        case 7: // 已评价
          url = `/pages/canceledOrder/index?order=${orderString}`;
          break;
        default: // 其他状态
          url = `/pages/orderDetails/index?order=${orderString}`;
          break;
      }
      wx.navigateTo({
        url: url,
        success: function () {
          // console.log("url",url);
          console.log("Navigation successful");
        },
        fail: function (err) {
          console.error("Navigation failed", err);
        }
      });



    } else {
      console.error("Order not found");
    }

  },

  clicKEvaluate(event) {
    console.log("event===========", event);
    event.stopPropagation(); // 阻止事件冒泡
    wx.navigateTo({
      url: '/packageOrder/pages/evaluate/index',
    })
  },

  // 去进度
  toSchedule(event){
    console.log("event===========", event.target.dataset.orderid);
    const orderId=event.target.dataset.orderid
    // event.stopPropagation(); // 阻止事件冒泡
    wx.navigateTo({
      url: `/packageOrder/pages/schedule/index?orderId=${orderId}`,
    })
  },

  toQuickOrder(){
    wx.switchTab({
      url: '/pages/quickOrder/index',
    })
  },
  toLogin(){
    wx.navigateTo({
      url: '/pages/login/index',
    })
  }

});